# 多项式回归 用 sklearn  6次多项式的数据
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression


x = np.linspace(-1, 1, 101).reshape(-1, 1)
num_cofffs = 6
coeffs = [1, 2, 3, 4, 5, 6]
Y_true = 0
for i in range(num_cofffs):
    Y_true += coeffs[i] * np.power(x, i)

print(Y_true.shape)
print(x.shape)

Y = Y_true + np.random.randn(*x.shape) * 1.5
plt.figure(1)
plt.scatter(x, Y)
# plt.show()
# plt.pause(1)


poly = PolynomialFeatures(degree=5)
XX = poly.fit_transform(x) #可打印出构造的X
print(XX)

model = LinearRegression().fit(XX, Y)
pred = model.predict(XX)

print('模型参数:', model.coef_, model.intercept_) # 输出模型参数

rmse = np.sqrt(mean_squared_error(Y, pred))
print(rmse)

plt.figure(1)
plt.plot(x, pred, 'r', label='predict')
plt.plot(x, Y_true, 'b', label='true')
plt.legend()
plt.show()
